package com.cmq.web_1.user_register;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebFilter("/*")
public class LoginFilter implements Filter {

    // 排除不需要登录的路径
    private static final List<String> EXCLUDED_PATHS = Arrays.asList(
            // 登录注册相关
            "/user-register/register.jsp",
            "/user-register/login.jsp",
            "/user-register/failure.jsp",
            "/register",
            "/login",
            // 购物车相关（必须放行）
            "/cart/products.jsp",   // 商品列表页
            "/cart/cart.jsp",       // 购物车页面
            "/cart",                // 购物车Servlet
            // 静态资源
            ".css", ".js", ".png", ".jpg", ".jpeg", ".gif"
    );

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String servletPath = httpRequest.getServletPath();

        // 排除路径直接放行
        if (isExcluded(servletPath)) {
            chain.doFilter(request, response);
            return;
        }

        // 其他路径需登录（不影响购物车功能）
        HttpSession session = httpRequest.getSession();
        Object loginUser = session.getAttribute("user");
        if (loginUser == null) {
            httpResponse.sendRedirect(httpRequest.getContextPath() + "/user-register/login.jsp");
        } else {
            chain.doFilter(request, response);
        }
    }

    private boolean isExcluded(String servletPath) {
        for (String path : EXCLUDED_PATHS) {
            if (path.startsWith(".")) {
                if (servletPath.endsWith(path)) return true;
            } else {
                if (servletPath.equals(path)) return true;
            }
        }
        return false;
    }

    @Override
    public void destroy() {}
}